const app = getApp();

Page({
  data: {
    userScore: 0,
    items: []
  },
  onLoad: function () {
    const token = app.globalData.token;
    if (!token) {
      wx.showToast({
        title: '未获取到有效token，请先登录',
        icon: 'none'
      });
      return;
    }
    // 获取用户分数
    this.getUserScore(token);
    // 获取奖品信息
    this.getItems(token);
  },
  getUserScore: function (token) {
    let url = 'http://8.140.225.174:5000/app/score';
    let header = {
      'content-type': 'application/x-www-form-urlencoded',
      'token': app.globalData.token
    };
    wx.request({
      url: url,
      method: 'GET',
      header: header,
      success: (res) => {
        if (res.data.code === 200 && res.data.data && res.data.data.length > 0) {
          this.setData({
            userScore: res.data.data[0].score
          });
        } else {
          wx.showToast({
            title: '获取分数失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.showToast({
          title: '网络错误，无法获取分数',
          icon: 'none'
        });
      }
    });
  },
  getItems: function (token) {
    let url = 'http://8.140.225.174:5000/item';
    let header = {
      'content-type': 'application/x-www-form-urlencoded',
      'token': app.globalData.token
    };
    wx.request({
      url: url,
      method: 'GET',
      header: header,
      success: (res) => {
        if (res.data.code === 200 && res.data.data) {
          this.setData({
            items: res.data.data
          });
        } else {
          wx.showToast({
            title: '获取奖品信息失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.showToast({
          title: '网络错误，无法获取奖品信息',
          icon: 'none'
        });
      }
    });
  },
  exchangeItem: function (e) {
    const itemId = e.currentTarget.dataset.itemid;
    const token = app.globalData.token;
    if (!token) {
      wx.showToast({
        title: '未获取到有效token，请先登录',
        icon: 'none'
      });
      return;
    }
    let url = 'http://8.140.225.174:5000/exchangeitem';
    let data = {
      ItemId: itemId
    };
    let header = {
      'content-type': 'application/x-www-form-urlencoded',
      'token': app.globalData.token
    };
    wx.request({
      url: url,
      method: 'POST',
      data: data,
      header: header,
      success: (res) => {
        if (res.data.code === 200 && res.data.data) {
          // 更新分数
          this.setData({
            userScore: res.data.data.score
          });
          wx.showToast({
            title: '兑换成功',
            icon: 'success'
          });
        } else {
          wx.showToast({
            title: '兑换失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.showToast({
          title: '网络错误，无法兑换物品',
          icon: 'none'
        });
      }
    });
  }
})